package com.stylefeng.guns.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author WG
 * @title: CmdUtil
 * @projectName guns-parent
 * @description: cmd
 * @date 2019/10/718:41
 */
public class CmdUtil {

    private final static Logger logger = LoggerFactory.getLogger(CmdUtil.class);

    public static String cmd(String commandStr) {
        BufferedReader br = null;
        try {
            //执行cmd命令
            Process p = Runtime.getRuntime().exec(commandStr);
            //返回值是流，以便读取。
            br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("UTF-8")));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                logger.info("执行状态 >>> " + line);
                sb.append(line + "\n");
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null){
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

}
